package com.wisdom.view;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

import com.hisun.phone.core.voice.Log4Util;
import com.wisdom.MainActivity;
import com.bluecall.sipua.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.sipdroid.sipua.ui.Receiver;
import org.sipdroid.sipua.ui.Settings;

import com.wisdom.VoiceApplication;
import com.wisdom.other.SystemScreenInfo;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.HttpUtil;
import com.wisdom.ui.AnimationTabHost;
import com.wisdom.util.UpdateManager;
import com.wisdom.voip.VoiceHelper;

public class HomeTabHostActivity extends TabActivity {
	private AnimationTabHost mTabHost;
	private TabWidget mTabWidget;
	private ImageView cursor;
	private int offset=0;
	private int currIndex=0;
	private int bmpW;
	private ImageView[] views;
    private ProgressDialog mDialog;
	public static final int WHAT_INIT_ERROR = 0x201C;
	private static HomeTabHostActivity mInstance;

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_hometabhost);
		mInstance = this;
		UpdateManager.getInstance().checkUpdate(mInstance);
		CCPConfig.initProperties(getApplicationContext());
		SystemScreenInfo.getSystemInfo(HomeTabHostActivity.this);
		InitImageView();
		mTabWidget=(TabWidget)findViewById(android.R.id.tabs);
		mTabHost=(AnimationTabHost)findViewById(android.R.id.tabhost);
		new Handler().postDelayed(new Runnable(){
			@Override
			public void run() {
				initBottomMenu();
			}
		},300);
		init();
		
	}
	
	@Override
	public void onStart(){
		super.onStart();
		if (CCPConfig.check()) {
			System.out.println("CCPConfig.check()---->true" );
			Receiver.engine(this).registerMore();
//			new LoginTask(CCPConfig.Src_phone, CCPConfig.Password);
		} else {
			System.out.println("CCPConfig.check()---->false" );
			startActivity(new Intent(HomeTabHostActivity.this,
					WelcomeActivity.class));
//			HomeTabHostActivity.this.finish();
		}
	}
	void showInitErrDialog(){
		new AlertDialog.Builder(this).setTitle(R.string.str_dialog_init_error_title)
				.setMessage(R.string.str_dialog_init_error_message)
				.setPositiveButton(R.string.dialog_btn,null).create().show();
	}
	
	class SDKInitAsyncTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			VoiceApplication va= VoiceApplication.getInstance();
			va.initVoiceHelper(helperHandler);
			return null;
		}
		@Override
		protected void onPostExecute(Void result){
			super.onPostExecute(result);
			mDialog.cancel();
		}
	}
	private void init(){
		setIndicator("拨号",0,new Intent(this,HomeDialActivity.class),R.drawable.tab_dial_selected);
		setIndicator("联系人",1,new Intent(this,HomeContactActivity.class),R.drawable.tab_contact_normal);
		//setIndicator("充值",2,new Intent(this,HomeSMSActivity.class),R.drawable.tab_sms_normal);
		setIndicator("充值",2,new Intent(this,HomePayActivity.class),R.drawable.tab_sms_normal);
		setIndicator("设置",3,new Intent(this,HomeSettingActivity.class),R.drawable.tab_settings_normal);
		
		mTabHost.setOpenAnimation(true);
	}
	private void setIndicator(String ss,int tabId,Intent intent,int image_id){
		View localView=LayoutInflater.from(this.mTabHost.getContext()).inflate(R.layout.tab_widget_view,null);
		((ImageView)localView.findViewById(R.id.main_activity_tab_image)).setImageResource(image_id);
		((TextView)localView.findViewById(R.id.main_activity_tab_text)).setText(ss);
		String str=String.valueOf(tabId);
		TabHost.TabSpec localTabSpec=mTabHost.newTabSpec(str).setIndicator(localView).setContent(intent);
		mTabHost.addTab(localTabSpec);
	}
	private void InitImageView(){
		cursor=(ImageView)findViewById(R.id.cursor);
		bmpW=BitmapFactory.decodeResource(getResources(), R.drawable.main_tab_anim_light).getWidth();
		DisplayMetrics dm=new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW=dm.widthPixels;
		offset=(screenW/4-bmpW)/2;
		Matrix matrix=new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);
	}
	
	private void initBottomMenu(){
		int viewCount=mTabWidget.getChildCount();
		views=new ImageView[viewCount];
		for(int i=0;i<views.length;i++){
			View v=(LinearLayout)mTabWidget.getChildAt(i);
			views[i]=(ImageView)v.findViewById(R.id.main_activity_tab_image);
		}
		mTabHost.setOnTabChangedListener(new OnTabChangeListener(){

			@Override
			public void onTabChanged(String tabId) {
				int tabID=Integer.valueOf(tabId);
				views[currIndex].setImageResource(getImageId(currIndex,false));
				views[tabID].setImageResource(getImageId(tabID,false));
				onPageSelected(tabID);
			}
			
		});
	}
	public void onPageSelected(int arg0){
		int one=offset*2+bmpW;
		Animation animation=null;
		animation=new TranslateAnimation(one*currIndex,one*arg0,0,0);
		currIndex=arg0;
		animation.setFillAfter(true);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}
	private int getImageId(int index,boolean isSelect){
		int result=-1;
		switch(index){
		case 0:
			result=isSelect?R.drawable.tab_dial_selected:R.drawable.tab_dial_normal;
			break;
		case 1:
			result=isSelect?R.drawable.tab_contact_selected:R.drawable.tab_contact_normal;
			break;
		case 2:
			result=isSelect?R.drawable.tab_sms_selected:R.drawable.tab_sms_normal;
			break;
		case 3:
			result=isSelect?R.drawable.tab_settings_selected:R.drawable.tab_settings_normal;
			break;
		}
		return result;
	}

	protected void onDestroy() {
		super.onDestroy();
	}
	private Handler helperHandler=new Handler(){
		 @Override
		 public void handleMessage(Message msg){
			 if(mDialog!=null){
				 mDialog.dismiss();
			 }
			 try{
				 if(msg.what==VoiceHelper.WHAT_ON_CONNECT){
					 if(!VoiceApplication.getInstance().isConnect()){
						 mDialog.cancel();
						 VoiceApplication.getInstance().setConnect(true);
					 }
				 }else if(msg.what==VoiceHelper.WHAT_ON_DISCONNECT){
					 // do nothing
				 }else if(msg.what==WHAT_INIT_ERROR){
					 if(!VoiceApplication.getInstance().isConnect()){
						 showInitErrDialog();
					 }
				 }else{
					 Log4Util.d(VoiceHelper.WISDOMCALL_TAG,"Sorry , can't handle a message " + msg.what);
				 }
			 }catch(Exception e){
				 
			 }
			 super.handleMessage(msg);
		 }
	};
	
	public class LoginTask extends AsyncTask<String, Void, JSONObject> {
		String phone;
		String pwd;
		
		public LoginTask(String telNum, String pwd){
			this.phone = telNum;
			this.pwd = pwd;
		}

		@Override
		protected void onPreExecute() {

			mDialog = new ProgressDialog(HomeTabHostActivity.this);
			mDialog.setMessage(getString(R.string.dialoglogon_message_text));
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(String... params) {

			JSONObject object;
			JSONObject data = null;
			try {
				object = new JSONObject("{Phone:\"" + phone + "\",Password=\""
						+ pwd + "\"}");
				data = HttpUtil.post(LoginActivity.LOGON_URL, object);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return data;

		}

		@Override
		protected void onPostExecute(JSONObject data) {
			mDialog.cancel();
			if (data == null) {
				Toast.makeText(getApplicationContext(), "未知错误！",
						Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				if (data.getBoolean("success")) {
					String accessToken = data.getString("AccessToken");
					String subAccount = data.getString("subAccount");
					String subToken = data.getString("subToken");
					String voipAccount = data.getString("voipAccount");
					String voipPwd = data.getString("voipPwd");
					String userId = data.getString("userId");
					String srcPhone = data.getString("srcPhone");
					String Balance = data.getString("balance");

					CCPConfig.setConfigProperties("accesstoken", accessToken);
					CCPConfig.setConfigProperties("sub_account", subAccount);
					CCPConfig.setConfigProperties("sub_token", subToken);
					CCPConfig.setConfigProperties("voip_account", voipAccount);
					CCPConfig.setConfigProperties("voip_password", voipPwd);
					CCPConfig.setConfigProperties("user_id", userId);
					CCPConfig.setConfigProperties("src_phone", srcPhone);
					CCPConfig.setConfigProperties("balance", Balance);
					CCPConfig.setConfigProperties("password", pwd);
					CCPConfig.initProperties(getApplicationContext());

					Editor edit = PreferenceManager
							.getDefaultSharedPreferences(HomeTabHostActivity.this)
							.edit();
					edit.putString(Settings.PREF_USERNAME, CCPConfig.Src_phone);
					edit.putString(Settings.PREF_PASSWORD, pwd);
					edit.putString(Settings.PREF_SERVER, CCPConfig.Sip_Server);
					edit.putString(Settings.PREF_DOMAIN,
							CCPConfig.Domain_Server);
					edit.putString(Settings.PREF_PORT, "5060");
					edit.commit();
//					Intent intent = new Intent();
//					intent.setClass(HomeTabHostActivity.this, HomeTabHostActivity.class);
//					startActivity(intent);
//					LoginActivity.this.finish();
				} else {
					Toast.makeText(getApplicationContext(),
							"登陆失败：" + data.getString("message"),
							Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
}

